package com.echo.register.commons.rabbitMQ;

import com.alibaba.fastjson.JSON;
import com.echo.register.domain.VoteCadidate;
import com.echo.register.domain.VoteDetailInfo;
import com.echo.register.domain.VoteRecords;
import com.echo.register.mapper.CadidateMapper;
import com.echo.register.mapper.DetailInfoMapper;
import com.echo.register.mapper.RecordsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @program: com.echo.voter
 * @description: 消息接收者
 * @author: Xiaoti
 * @create: 2018-11-05 16:40
 **/
@Service
public class MQRecevier {

    private static Logger logger = LoggerFactory.getLogger(MQRecevier.class);

    @Resource
    CadidateMapper cadidateMapper;
    @Resource
    DetailInfoMapper detailInfoMapper;
    @Resource
    RecordsMapper recordsMapper;

    @RabbitListener(queues = MQConfig.VOTE_QUEUE)
    public void receiveVoteMessage(String message) {
        logger.info("receive message is {}", message);
        VoteMessage voteMessage = stringToBean(message, VoteMessage.class);
        VoteCadidate cadidate = voteMessage.getCadidate();

        //更新数据库票数
        cadidateMapper.updateCadidate(cadidate);
    }

    @RabbitListener(queues = MQConfig.DETAIL_QUEUE)
    public void receiveDetailmessage(String message) {
        logger.info("receive message is {}", message);
        DetailMessage detailMessage = stringToBean(message, DetailMessage.class);

        VoteDetailInfo detailInfo = detailMessage.getVoteDetailInfo();
        detailInfoMapper.insertDetailInfo(detailInfo);
    }

    @RabbitListener(queues = MQConfig.RECORDS_QUEUE)
    public void receiveRecordsMessage(String message) {
        logger.info("receive message is {}", message);
        RecordsMessage recordsMessage = stringToBean(message, RecordsMessage.class);
        VoteRecords records = recordsMessage.getVoteRecords();

        recordsMapper.updateRecords(records);
    }

    private <T> T stringToBean(String str, Class<T> clazz) {
        if (str == null || str.length() <= 0 || clazz == null) {
            return null;
        }
        if (clazz == int.class || clazz == Integer.class) {
            return (T) Integer.valueOf(str);
        } else if (clazz == String.class) {
            return (T) str;
        } else if (clazz == long.class || clazz == Long.class) {
            return (T) Long.valueOf(str);
        } else {
            return JSON.toJavaObject(JSON.parseObject(str), clazz);
        }
    }
}
